package com.lej.club.wxapi

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.lej.core.utils.KLog
import com.lej.pay.BuildConfig
import com.lej.wx.data.WxStatus
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory

class WXPayEntryActivity : Activity(), IWXAPIEventHandler {
    private var api: IWXAPI? = null
    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        api = WXAPIFactory.createWXAPI(this, BuildConfig.WX_APP_ID)
        api?.handleIntent(intent, this)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        api?.handleIntent(intent, this)
    }

    override fun onReq(req: BaseReq) {}
    override fun onResp(resp: BaseResp) {
        if (resp.type == ConstantsAPI.COMMAND_PAY_BY_WX) {
            KLog.e("callback data" + resp.errCode)
            when (resp.errCode) {
                BaseResp.ErrCode.ERR_OK -> block?.invoke(WxStatus.WX_OK, "")
                BaseResp.ErrCode.ERR_USER_CANCEL -> block?.invoke(WxStatus.WX_CANCEL, "用户取消")
                else -> block?.invoke(WxStatus.WX_ERROR, resp.errStr)
            }
        }
        super.finish()
    }

    override fun finish() {
        KLog.i("user exit pay page")
        block?.invoke(WxStatus.WX_CANCEL, "取消")
        super.finish()
    }

    companion object {
        var block: ((WxStatus, String) -> Unit)? = null
    }
}